package com.atguigu.gmall.all.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.product.client.ProductFeignClient;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：MJS
 * @date ：Created in 2021/5/15  9:39
 * @description：TODO
 */
@Controller
@Api(description = "api页面首页")
public class IndexController {
    @Autowired
    private ProductFeignClient productFeignClient;
    //http://www.gmall.com
    @GetMapping("/")
    public String index(Model model){
        List<Map> result = buildData();
        model.addAttribute("list",result);
        return "index/index";
    }

    private List<Map> buildData() {
        //三级分类视图集合
        List<BaseCategoryView> baseCategoryViewList = productFeignClient.getBaseCategoryViewList();
        //stream流
        //Long：K  一级分类ID  分组字段
        //List<BaseCategoryView>  分组后集合
       /* Map<Long, List<BaseCategoryView>> baseCategoryViewListGroup = baseCategoryViewList.stream().
                collect(Collectors.groupingBy(baseCategoryView -> {
            return baseCategoryView.getCategory1Id();
        }));*/
        //BaseCategoryView代表入参   getCategory1Id代表返回值
        Map<Long, List<BaseCategoryView>> category1ListGroup = baseCategoryViewList.stream().
                collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        //方法一：
        //POJO
        //categoryId
        //categoryName
        //List<POJO>categoryChild
        //方法二：此方式适用任何类型
        //无敌POJO  Map
        //map.put(categoryId,V);
        //map.put(categoryName,V);
        //map.put(categoryChild,List<>);

        //最终结果集合
        List<Map>result=new ArrayList<>();
        //行号
        int index=1;
        for (Map.Entry<Long, List<BaseCategoryView>> category1Entry :
                category1ListGroup.entrySet()) {
    /*        category1Entry.getKey()   //一级分类Id
            category1Entry.getValue()  //一级分类ID对应的集合*/
            Map category1Map=new HashMap();
            category1Map.put("index",index++);
            category1Map.put("categoryId",category1Entry.getKey());
            List<BaseCategoryView> category1List = category1Entry.getValue();
            category1Map.put("categoryName",category1List.get(0).getCategory1Name());
            //二级分类的集合
            List<Map>category2ListMap=new ArrayList<>();
            Map<Long, List<BaseCategoryView>> category2ListGroup = category1List.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            for (Map.Entry<Long, List<BaseCategoryView>> category2Entry :
                    category2ListGroup.entrySet()) {
                Map category2Map=new HashMap();
                category2Map.put("categoryId",category2Entry.getKey());
                List<BaseCategoryView> category2List = category2Entry.getValue();
                category2Map.put("categoryName",category2List.get(0).getCategory2Name());

             //==================================================
                //三级分类集合
                List<Map>category3ListMap=new ArrayList<>();
                for (BaseCategoryView baseCategoryView : category2List) {
                    Map category3Map=new HashMap();
                    category3Map.put("categoryId",baseCategoryView.getCategory3Id());
                    category3Map.put("categoryName",baseCategoryView.getCategory3Name());
                    category3ListMap.add(category3Map);
                }
             //==================================================

                category2Map.put("categoryChild",category3ListMap);
                category2ListMap.add(category2Map);
            }



            //==================================================
            category1Map.put("categoryChild",category2ListMap);
            result.add(category1Map);
        }
        return result;
    }

    //使用静态化技术生成页面   win10 D:\test\index.html
    @Autowired
    private TemplateEngine templateEngine; //模板引擎
    //生成静态化页面  （方法1：人为触发  方法2：定时器）
    @GetMapping("/createHtml")
    @ResponseBody
    public Result createHtml(){
        //重点：如何使用静态化 生成页面
        //thymeleaf:  页面标签    静态化技术   ：将有标签页面  模板 .html+数据=渲染=输出（无标签页面页面）
        //数据
        Context context=new Context();
        context.setVariable("list",buildData());
        //输出流
        Writer writer=null;
        try {
            //乱码问题
            //读：utf-8
            //写：utf-8
//             writer=new OutputStreamWriter(new FileOutputStream("D:\\test\\index.html"),"utf-8");
            writer=new PrintWriter("D:\\temp\\index.html","utf-8");
             //渲染
            templateEngine.process("index/index",context,writer);//处理==渲染
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //先判断，防止空指针异常
                if(writer !=null){
                    writer.close();//空指针异常
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return Result.ok();
    }
}
